package com.xiemulei.gulimall.cart.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import com.xiemulei.common.utils.R;
import com.xiemulei.gulimall.cart.feign.ProductFeignClient;
import com.xiemulei.gulimall.cart.interceptor.CartInterceptor;
import com.xiemulei.gulimall.cart.service.CartService;
import com.xiemulei.gulimall.cart.vo.Cart;
import com.xiemulei.gulimall.cart.vo.CartItem;
import com.xiemulei.gulimall.cart.vo.SkuInfoVo;
import com.xiemulei.gulimall.cart.vo.UserInfoTo;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl implements CartService {
    private static final String CART_PREFIX = "gulimall:cart:";

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Resource
    ProductFeignClient productFeignClient;

    @Resource
    ThreadPoolExecutor executor;

    @Override
    public CartItem addCartItem(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> operations = getCartOperations();
        // 判断商品是否已经在购物车中
        String result = (String) operations.get(skuId.toString());
        CartItem cartItem;
        if (!StringUtils.hasLength(result)) {
            cartItem = new CartItem();
            CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {
                R info = productFeignClient.getSkuInfo(skuId);
                SkuInfoVo skuInfo = info.getData("skuInfo", new TypeReference<>() {
                });

                cartItem.setSkuId(skuId);
                cartItem.setCheck(true);
                cartItem.setCount(num);
                cartItem.setImage(skuInfo.getSkuDefaultImg());
                cartItem.setTitle(skuInfo.getSkuTitle());
                cartItem.setPrice(skuInfo.getPrice());
            }, executor);


            // 远程查询 sku 的组合信息
            CompletableFuture<Void> getSkuSaleAttrValuesTask = CompletableFuture.runAsync(() -> {
                List<String> skuSaleAttrValues = productFeignClient.getSkuSaleAttrValues(skuId);
                cartItem.setSkuAttr(skuSaleAttrValues);
            }, executor);

            CompletableFuture.allOf(getSkuInfoTask, getSkuSaleAttrValuesTask).get();

            String s = JSON.toJSONString(cartItem);
            operations.put(skuId.toString(), s);
        } else {
            // 购物车中有此商品，修改数量
            cartItem = JSON.parseObject(result, CartItem.class);
            cartItem.setCount(cartItem.getCount() + num);
            operations.put(skuId.toString(), JSON.toJSONString(cartItem));
        }
        return cartItem;
    }

    private BoundHashOperations<String, Object, Object> getCartOperations() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String cartKey;
        if (userInfoTo.getUserId() != null) {
            cartKey = CART_PREFIX + userInfoTo.getUserId();
        } else {
            cartKey = CART_PREFIX + userInfoTo.getUserKey();
        }

        return stringRedisTemplate.boundHashOps(cartKey);
    }

    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOperations = getCartOperations();
        String str = (String) cartOperations.get(skuId.toString());
        return JSON.parseObject(str, CartItem.class);
    }

    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {
        Cart cart = new Cart();
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId() != null) {
            //已登录
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            // 合并临时购物车中的商品数据
            String tempCartKey = CART_PREFIX + userInfoTo.getUserKey();
            List<CartItem> tempCartItems = getCartItems(tempCartKey);
            if (tempCartItems != null) {
                for (CartItem item : tempCartItems) {
                    addCartItem(item.getSkuId(), item.getCount());
                }
                //清空临时购物车
                clearCart(tempCartKey);
            }
            // 获取所有数据
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);

        } else {
            //未登录
            String cartKey = CART_PREFIX + userInfoTo.getUserKey(); // 临时购物车
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);
        }
        return cart;
    }

    @Override
    public void clearCart(String cartKey) {
        stringRedisTemplate.delete(cartKey);
    }

    @Override
    public void checkItem(Long skuId, Integer checked) {
        BoundHashOperations<String, Object, Object> cartOperations = getCartOperations();
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(checked == 1);
        String s = JSON.toJSONString(cartItem);
        cartOperations.put(skuId.toString(), s);
    }

    @Override
    public void countItem(Long skuId, Integer num) {
        BoundHashOperations<String, Object, Object> cartOperations = getCartOperations();
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(num);
        String s = JSON.toJSONString(cartItem);
        cartOperations.put(skuId.toString(), s);
    }

    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOperations = getCartOperations();
        if (Boolean.TRUE.equals(cartOperations.hasKey(skuId.toString()))) {
            cartOperations.delete(skuId.toString());
        }
    }

    @Override
    public List<CartItem> getUserCartItems() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId() == null) {
            return null;
        } else {
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            List<CartItem> cartItems = getCartItems(cartKey);
            assert cartItems != null;
            return cartItems.stream().filter(CartItem::getCheck)
                    .peek(cartItem -> {
                        //获取最新商品价格
                        BigDecimal price = productFeignClient.getPrice(cartItem.getSkuId());
                        cartItem.setPrice(price);
                    }).collect(Collectors.toList());
        }

    }


    private List<CartItem> getCartItems(String cartKey) {
        BoundHashOperations<String, Object, Object> hashOps = stringRedisTemplate.boundHashOps(cartKey);
        List<Object> values = hashOps.values();
        if (values != null && values.size() > 0) {
            return values.stream().map((obj) -> {
                String str = (String) obj;
                return JSON.parseObject(str, CartItem.class);
            }).collect(Collectors.toList());
        }
        return null;
    }
}
